package com.eric.service.impl;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.eric.domain.po.table.UnitNameTableDef;
import com.eric.domain.vo.UnitNameVO;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.eric.domain.po.UnitName;
import com.eric.mapper.UnitNameMapper;
import com.eric.service.UnitNameService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  服务层实现。
 *
 * @author eric.deng
 * @since 2025-03-05
 */
@Service
public class UnitNameServiceImpl extends ServiceImpl<UnitNameMapper, UnitName>  implements UnitNameService{

    @Override
    public SaResult saveOne(UnitNameVO unitNameVO) {
        String unitName_ = unitNameVO.getUnitName();
        if (StrUtil.isBlank(unitName_)){
            return SaResult.error("单位名称不能为空！");
        }
        String unitName2_final ="元/"+unitName_;
        unitNameVO.setUnitName(unitName2_final);
        UnitName unitName = queryChain().select()
                .where(UnitNameTableDef.UNIT_NAME.UNIT_NAME_.eq(unitNameVO.getUnitName()))
                .one();
        boolean empty = BeanUtil.isEmpty(unitName);
        if (empty){
            UnitName unitNameInsert=new UnitName();
            BeanUtil.copyProperties(unitNameVO,unitNameInsert);
            boolean save = save(unitNameInsert);
            return  save? SaResult.ok("已录入！") : (SaResult.error("录入错误"));
        }
        return SaResult.error("单位名称已经存在！");
    }

    @Override
    public SaResult removeOneById(Long id) {
        boolean b = removeById(id);
        return b? SaResult.ok("删除成功！"):SaResult.error("删除失败！");

    }

    @Override
    public SaResult updateOne(UnitNameVO unitNameVO) {
        boolean empty = BeanUtil.isEmpty(unitNameVO);
        if (empty){
            return SaResult.error("参数错误！");
        }
        if (unitNameVO.getId()==null){
            return SaResult.error("id不能为空！");
        }
        boolean unitNameEffective=false;
        if (!StrUtil.isBlank(unitNameVO.getUnitName())){
            unitNameEffective=true;
        }
        List<UnitName> list = queryChain().where(UnitNameTableDef.UNIT_NAME.UNIT_NAME_.eq(unitNameVO.getUnitName())).list();
        if (!list.isEmpty()){
            return SaResult.error("单位名称已经存在！");
        }

        boolean update = UpdateChain.of(UnitName.class)
                .set(UnitNameTableDef.UNIT_NAME.UNIT_NAME_, unitNameVO.getUnitName(), unitNameEffective)
                .where(UnitNameTableDef.UNIT_NAME.ID.eq(unitNameVO.getId()))
                .update();


        return update? SaResult.ok("更新成功！"):SaResult.error("更新失败！");
    }
}
